import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Layout, message } from 'antd';
import { io, Socket } from 'socket.io-client';
import HistoryList from './components/HistoryList/HistoryList';
import ChatContent from './components/ChatContent/ChatContent';
import DataTable from './components/DataTable/DataTable';
import './KimiChat.scss';

const { Sider, Content } = Layout;

export interface ChatMessage {
    id: string;
    content: string;
    timestamp: Date;
    type: 'user' | 'assistant' | 'system';
    messageType: 'readonly' | 'audit';
    status?: 'pending' | 'approved' | 'rejected';
    conversationId: string;
}

export interface Conversation {
    id: string;
    title: string;
    messages: ChatMessage[];
    tableData: TableData[];
    createdAt: Date;
    updatedAt: Date;
}

export interface TableData {
    id: string;
    name: string;
    value: number;
    category: string;
    status: string;
    date: string;
    conversationId: string;
}

const KimiChat: React.FC = () => {
    const [conversations, setConversations] = useState<Conversation[]>([]);
    const [currentConversationId, setCurrentConversationId] = useState<string | null>(null);
    const [isConnected, setIsConnected] = useState(false);
    const [connectionError, setConnectionError] = useState<string | null>(null);
    const socket = useRef<Socket | null>(null);

    const currentConversation = conversations.find(conv => conv.id === currentConversationId);

    // 创建新对话
    const handleCreateConversation = useCallback(() => {
        const newConversation: Conversation = {
            id: `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            title: `对话 ${conversations.length + 1}`,
            messages: [],
            tableData: [],
            createdAt: new Date(),
            updatedAt: new Date()
        };
        setConversations(prev => [newConversation, ...prev]);
        setCurrentConversationId(newConversation.id);
    }, [conversations.length]);

    // 删除对话
    const handleDeleteConversation = useCallback((conversationId: string) => {
        setConversations(prev => prev.filter(conv => conv.id !== conversationId));
        if (currentConversationId === conversationId) {
            setCurrentConversationId(null);
        }
    }, [currentConversationId]);

    // 选择对话
    const handleSelectConversation = useCallback((conversationId: string) => {
        setCurrentConversationId(conversationId);
    }, []);

    // 发送消息
    const handleSendMessage = useCallback((content: string) => {
        if (!currentConversationId || !socket.current) {
            message.error('请先选择对话或检查连接状态');
            return;
        }

        const userMessage: ChatMessage = {
            id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            content,
            timestamp: new Date(),
            type: 'user',
            messageType: 'readonly',
            conversationId: currentConversationId
        };

        // 添加用户消息到当前对话
        setConversations(prev => prev.map(conv => {
            if (conv.id === currentConversationId) {
                return {
                    ...conv,
                    messages: [...conv.messages, userMessage],
                    updatedAt: new Date()
                };
            }
            return conv;
        }));

        // 发送消息到服务器
        socket.current.emit('user_message', {
            conversationId: currentConversationId,
            message: content,
            messageId: userMessage.id
        });
    }, [currentConversationId]);

    // 处理审核操作
    const handleAuditAction = useCallback((messageId: string, action: 'approve' | 'reject') => {
        if (!socket.current || !currentConversationId) return;

        // 更新消息状态
        setConversations(prev => prev.map(conv => {
            if (conv.id === currentConversationId) {
                return {
                    ...conv,
                    messages: conv.messages.map(msg => {
                        if (msg.id === messageId) {
                            return {
                                ...msg,
                                status: action === 'approve' ? 'approved' : 'rejected'
                            };
                        }
                        return msg;
                    }),
                    updatedAt: new Date()
                };
            }
            return conv;
        }));

        // 发送审核结果到服务器
        socket.current.emit('audit_response', {
            conversationId: currentConversationId,
            messageId,
            action
        });
    }, [currentConversationId]);

    // 初始化Socket.IO连接
    const initializeSocket = useCallback(() => {
        if (socket.current) {
            socket.current.disconnect();
        }

        socket.current = io('http://localhost:8080', {
            transports: ['websocket'],
            timeout: 5000
        });

        // socket.current = io('http://localhost:5000', {
        //     path: '/socket.io',  // 使用SocketIO默认路径
        //     transports: ['websocket'],
        //     timeout: 5000
        // });

        // 连接事件
        socket.current.on('connect', () => {
            console.log('Socket.IO连接已建立:', socket.current?.id);
            setIsConnected(true);
            setConnectionError(null);
        });

        // 连接响应
        socket.current.on('connect_response', (data) => {
            console.log('连接响应:', data);
            message.success('连接成功');
        });

        // 匹配更新
        socket.current.on('match_update', (data) => {
            console.log('匹配更新:', data);
            if (data.conversationId && currentConversationId === data.conversationId) {
                const assistantMessage: ChatMessage = {
                    id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    content: data.content || '匹配更新',
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'readonly',
                    conversationId: data.conversationId
                };

                setConversations(prev => prev.map(conv => {
                    if (conv.id === data.conversationId) {
                        return {
                            ...conv,
                            messages: [...conv.messages, assistantMessage],
                            updatedAt: new Date()
                        };
                    }
                    return conv;
                }));
            }
        });

        // 匹配完成
        socket.current.on('match_complete', (data) => {
            console.log('匹配完成:', data);
            if (data.conversationId && currentConversationId === data.conversationId) {
                const completeMessage: ChatMessage = {
                    id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    content: data.content || '匹配完成',
                    timestamp: new Date(),
                    type: 'system',
                    messageType: 'readonly',
                    conversationId: data.conversationId
                };

                setConversations(prev => prev.map(conv => {
                    if (conv.id === data.conversationId) {
                        return {
                            ...conv,
                            messages: [...conv.messages, completeMessage],
                            updatedAt: new Date()
                        };
                    }
                    return conv;
                }));

                // 更新表格数据
                if (data.tableData) {
                    setConversations(prev => prev.map(conv => {
                        if (conv.id === data.conversationId) {
                            return {
                                ...conv,
                                tableData: [...conv.tableData, ...data.tableData],
                                updatedAt: new Date()
                            };
                        }
                        return conv;
                    }));
                }
            }
        });

        // 审核请求
        socket.current.on('audit_request', (data) => {
            console.log('审核请求:', data);
            if (data.conversationId && currentConversationId === data.conversationId) {
                const auditMessage: ChatMessage = {
                    id: data.messageId || `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    content: data.content || '需要审核',
                    timestamp: new Date(),
                    type: 'assistant',
                    messageType: 'audit',
                    status: 'pending',
                    conversationId: data.conversationId
                };

                setConversations(prev => prev.map(conv => {
                    if (conv.id === data.conversationId) {
                        return {
                            ...conv,
                            messages: [...conv.messages, auditMessage],
                            updatedAt: new Date()
                        };
                    }
                    return conv;
                }));
            }
        });

        // 审核更新
        socket.current.on('audit_update', (data) => {
            console.log('审核更新:', data);
            if (data.conversationId && currentConversationId === data.conversationId) {
                setConversations(prev => prev.map(conv => {
                    if (conv.id === data.conversationId) {
                        return {
                            ...conv,
                            messages: conv.messages.map(msg => {
                                if (msg.id === data.messageId) {
                                    return {
                                        ...msg,
                                        status: data.status,
                                        content: data.content || msg.content
                                    };
                                }
                                return msg;
                            }),
                            updatedAt: new Date()
                        };
                    }
                    return conv;
                }));

                // 更新表格数据
                if (data.tableData) {
                    setConversations(prev => prev.map(conv => {
                        if (conv.id === data.conversationId) {
                            return {
                                ...conv,
                                tableData: [...conv.tableData, ...data.tableData],
                                updatedAt: new Date()
                            };
                        }
                        return conv;
                    }));
                }
            }
        });

        // 断开连接
        socket.current.on('disconnect', (reason) => {
            console.log('Socket.IO连接断开:', reason);
            setIsConnected(false);
            message.warning('连接已断开');
        });

        // 错误处理
        socket.current.on('error', (error) => {
            console.error('Socket.IO错误:', error);
            setConnectionError(error.message || '连接错误');
            message.error('连接错误: ' + (error.message || '未知错误'));
        });

        // 连接错误
        socket.current.on('connect_error', (error) => {
            console.error('Socket.IO连接错误:', error);
            setConnectionError(error.message || '连接失败');
            setIsConnected(false);
            message.error('连接失败: ' + (error.message || '服务器不可达'));
        });
    }, [currentConversationId]);

    // 组件挂载时初始化连接
    useEffect(() => {
        initializeSocket();

        return () => {
            if (socket.current) {
                socket.current.disconnect();
            }
        };
    }, [initializeSocket]);

    // 创建默认对话
    useEffect(() => {
        if (conversations.length === 0) {
            handleCreateConversation();
        }
    }, [conversations.length, handleCreateConversation]);

    return (
        <Layout className="kimi-chat">
            <Sider width={280} className="kimi-chat__sidebar">
                <HistoryList
                    conversations={conversations}
                    currentConversationId={currentConversationId}
                    onCreateConversation={handleCreateConversation}
                    onDeleteConversation={handleDeleteConversation}
                    onSelectConversation={handleSelectConversation}
                    isConnected={isConnected}
                    connectionError={connectionError}
                />
            </Sider>
            <Content className="kimi-chat__main">
                <div className="kimi-chat__content">
                    <ChatContent
                        conversation={currentConversation}
                        onSendMessage={handleSendMessage}
                        onAuditAction={handleAuditAction}
                        isConnected={isConnected}
                        socket={socket}
                    />
                </div>
            </Content>
            <Sider width={320} className="kimi-chat__data-panel">
                <DataTable
                    tableData={currentConversation?.tableData || []}
                    conversationId={currentConversationId}
                />
            </Sider>
        </Layout>
    );
};

export default KimiChat;